package com.runjian.rundo.iot.agent.business.control.publisher;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.hutool.core.collection.ListUtil;
import org.springframework.context.event.EventListener;

import com.runjian.rundo.iot.agent.business.control.config.ControlConfigurationProperties;
import com.runjian.rundo.iot.agent.business.control.event.DeviceControlResponseEvent;
import com.runjian.rundo.iot.agent.business.publisher.MessagePublisher;
import com.runjian.rundo.iot.agent.common.entity.CommonDeviceCommand;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 设备控制回复消息处理器
 *
 * @author LiGang
 */
@Slf4j
@RequiredArgsConstructor
public class DeviceControlRespMessageProcessor {

    private final ControlConfigurationProperties controlConfigurationProperties;

    private final MessagePublisher messagePublisher;

    @EventListener(classes = DeviceControlResponseEvent.class)
    public void handleControlResponse(DeviceControlResponseEvent deviceControlResponseEvent) {
        log.info("[设备控制响应] 接收到设备控制响应消息，开始处理设备控制响应消息");

        CommonDeviceCommand commonDeviceCommand = deviceControlResponseEvent.getDeviceCommand();
        String traceId = commonDeviceCommand.getTraceId();
        if (traceId == null) {
            log.info("[设备控制响应] 不存在控制traceId,不发送设备控制响应结果到服务端");
            return;
        }
        Set<String> callBackSeries = null;
        if (StrUtil.isNotEmpty(deviceControlResponseEvent.getSeries())) {
            // 只返馈这个指标项
            callBackSeries = new HashSet(ListUtil.of(deviceControlResponseEvent.getSeries()));
        } else {
            callBackSeries = commonDeviceCommand.getRemainingKeys();
        }
        for (String callBackSerie : callBackSeries) {
            // 全部反馈回去
            commonDeviceCommand.addCallbackSeries(callBackSerie);
            deviceControlResponseEvent.setSeries(callBackSerie);
            this.messagePublisher.send(controlConfigurationProperties.getControlCallbackTopic(), deviceControlResponseEvent);
        }
    }
}
